<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-06-08
 * Time: 16:13:57
 * Info:
 */

namespace app\admin\controller\system;

use app\admin\annotation\ControllerAnnotation;
use app\admin\annotation\NodeAnotation;
use app\admin\controller\CommonController;
use support\Request;
use xianrenqh\Task\Client;
use think\facade\Db;
use support\lib\Crontab;

/**
 * @ControllerAnnotation(title="定时任务管理")
 * Class Node
 * @package app\admin\controller\system
 */
class CrontabController extends CommonController
{

    /**
     * @NodeAnotation(title="任务列表")
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $limit = (int)$request->input('limit', 10);
            $page  = (int)$request->input('page', 1);
            $key   = $request->input('key');
            $first = ($page - 1) * $limit;
            $where = function ($query) use ($key) {
                if ( ! empty($key['title'])) {
                    $query->whereLike('title', '%'.$key['title'].'%');
                }
                if (isset($key['status']) && $key['status'] != '') {
                    $query->where('status', $key['status']);
                }
            };
            $total = Db::table('system_crontab')->where($where)->count();
            $list  = Db::table('system_crontab')->where($where)->limit($first,
                $limit)->order('sort asc,id desc')->select()->toArray();
            foreach ($list as $key => $v) {
                $list[$key]['create_time']       = date('Y-m-d H:i:s', $v['create_time']);
                $list[$key]['last_running_time'] = date('Y-m-d H:i:s', $v['last_running_time']);
                switch ($v['type']) {
                    case 1:
                        $list[$key]['type_name'] = "command";
                        break;
                    case 2:
                        $list[$key]['type_name'] = "class";
                        break;
                    case 3:
                        $list[$key]['type_name'] = "url";
                        break;
                    case 4:
                        $list[$key]['type_name'] = "eval";
                        break;
                    case 5:
                        $list[$key]['type_name'] = "shell";
                        break;
                }
            }

            return $this->success("ok", $list, $total);
        }

        return view('crontab/index');

    }

    /**
     * @NodeAnotation(title="添加任务")
     */
    public function add(Request $request)
    {
        if ($request->isPost()) {
            $param       = $request->all();
            $crontabLib  = new Crontab();
            $crontab_r   = $crontabLib->GetCrondCycle($param);
            $rule_params = [
                'time_cycle' => $param['time_cycle'],
                'week'       => ! empty($param['week']) ? $param['week'] : '',
                'hour'       => ! empty($param['hour']) ? $param['hour'] : '',
                'minute'     => ! empty($param['minute']) ? $param['minute'] : '',
                'second'     => ! empty($param['second']) ? $param['second'] : '',
                'where1'     => ! empty($param['where1']) ? $param['where1'] : '',
            ];
            $request     = [
                'method' => 'crontabCreate',
                'args'   => [
                    'title'       => $param['title'],
                    'type'        => $param['type'],
                    'rule'        => $crontab_r,
                    'rule_params' => json_encode($rule_params),
                    'target'      => $param['target'],
                    'status'      => $param['status'],
                    'remark'      => $param['remark'],
                    'singleton'   => $param['singleton'],
                    'sort'        => $param['sort'],
                    'create_time' => time(),
                    'update_time' => time()
                ]
            ];
            $result      = Client::instance()->request($request);
            if ($result->code == 200) {
                return $this->success('新增成功');
            } else {
                return error_json('error');
            }
        }

        return view('crontab/add');

    }

    /**
     * @NodeAnotation(title="编辑任务")
     */
    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $param       = $request->all();
            $crontabLib  = new Crontab();
            $crontab_r   = $crontabLib->GetCrondCycle($param);
            $rule_params = [
                'time_cycle' => $param['time_cycle'],
                'week'       => ! empty($param['week']) ? $param['week'] : '',
                'hour'       => ! empty($param['hour']) ? $param['hour'] : '',
                'minute'     => ! empty($param['minute']) ? $param['minute'] : '',
                'second'     => ! empty($param['second']) ? $param['second'] : '',
                'where1'     => ! empty($param['where1']) ? $param['where1'] : '',
            ];
            $request     = [
                'method' => 'crontabUpdate',
                'args'   => [
                    'id'          => $param['id'],
                    'rule'        => $crontab_r,
                    'rule_params' => json_encode($rule_params),
                    'target'      => $param['target'],
                    'status'      => $param['status'],
                    'remark'      => $param['remark'],
                    'singleton'   => $param['singleton'],
                    'sort'        => $param['sort'],
                    'update_time' => time()
                ]
            ];
            $result      = Client::instance()->request($request);
            if ($result->code == 200) {
                return $this->success('更改成功');
            } else {
                return error_json('error');
            }
        }

        $id   = $request->get('id');
        $data = Db::table('system_crontab')->where('id', $id)->find();

        $data['rule_params'] = json_decode($data['rule_params'], true);
        if (empty($data['rule_params'])) {
            $data['rule_params']['time_cycle'] = '';
            $data['rule_params']['week']       = '';
            $data['rule_params']['hour']       = '';
            $data['rule_params']['minute']     = '';
            $data['rule_params']['second']     = '';
            $data['rule_params']['where1']     = '';
        }

        return view('crontab/edit', ['data' => $data]);
    }

    /**
     * @NodeAnotation(title="重启任务")
     */
    public function reload(Request $request)
    {
        if ($request->isPost()) {
            $id     = $request->post('id');
            $param  = [
                'method' => 'crontabReload',
                'args'   => [
                    'id' => $id
                ]
            ];
            $result = Client::instance()->request($param);
            if ($result->code == 200) {
                return $this->success('重启成功');
            } else {
                return error_json('error');
            }

        }
    }

    /**
     * @NodeAnotation(title="删除任务")
     */
    public function delete(Request $request)
    {
        $id     = $request->get('id');
        $param  = [
            'method' => 'crontabDelete',
            'args'   => [
                'id' => $id
            ]
        ];
        $result = Client::instance()->request($param);
        if ($result->code == 200) {
            return $this->success('删除成功');
        } else {
            return error_json('error');
        }
    }

    /**
     * @NodeAnotation(title="更改状态")
     */
    public function status(Request $request)
    {
        if ($request->isPost()) {
            $id      = $request->get('id');
            $status  = $request->post('val');
            $request = [
                'method' => 'crontabUpdate',
                'args'   => [
                    'id'     => $id,
                    'status' => $status,
                ]
            ];
            $result  = Client::instance()->request($request);
            if ($result->code == 200) {
                if ($status == 1) {
                    $msg = "状态启用成功";
                } else {
                    $msg = "状态禁用成功";
                }

                return $this->success($msg);
            } else {
                return error_json('error');
            }
        }

    }

    /**
     * @NodeAnotation(title="日志列表")
     */
    public function logList(Request $request)
    {
        if ($request->isAjax()) {
            $limit      = (int)$request->input('limit', 10);
            $page       = (int)$request->input('page', 1);
            $first      = ($page - 1) * $limit;
            $crontab_id = $request->input('crontab_id');
            $list       = Db::table('system_crontab_log')->where('crontab_id',
                $crontab_id)->order('id desc')->limit($first, $limit)->select()->toArray();
            foreach ($list as $key => $v) {
                $list[$key]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
            $total = Db::table('system_crontab_log')->where('crontab_id', $crontab_id)->count();

            return $this->success("ok", $list, $total);
        }
        $id = $request->input('id');

        return view('crontab/log_list', ['crontab_id' => $id]);
    }

}
